import React, { useState, useEffect, useMemo } from 'react';
import { Card, Row, Col, Statistic, Progress, Table, Tabs, Timeline, Alert, Spin } from 'antd';
import {
  ThunderboltOutlined,
  DatabaseOutlined,
  ApiOutlined,
  ClockCircleOutlined,
  WarningOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import { useCache } from '@hooks/useCache';
import { usePerformanceMonitor } from '@hooks/usePerformance';
import WebVitalsMonitor from '@components/Performance/WebVitalsMonitor';


/**
 * 性能数据接口
 */
interface PerformanceData {
  timestamp: number;
  cpu: number;
  memory: number;
  disk: number;
  network: number;
  responseTime: number;
  throughput: number;
  errorRate: number;
}

/**
 * 性能建议接口
 */
interface PerformanceRecommendation {
  id: string;
  type: 'critical' | 'warning' | 'info';
  category: 'frontend' | 'backend' | 'database' | 'network';
  title: string;
  description: string;
  impact: 'high' | 'medium' | 'low';
  solution: string;
}

/**
 * 性能仪表板组件
 */
const PerformanceDashboard: React.FC = () => {
  // 性能监控
  const { renderCount, averageRenderTime } = usePerformanceMonitor('PerformanceDashboard');

  // 状态管理
  const [performanceData, setPerformanceData] = useState<PerformanceData[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedTimeRange, setSelectedTimeRange] = useState('1h');

  /**
   * 获取后端性能指标
   */
  const fetchBackendMetrics = async () => {
    // 模拟API调用
    return {
      cpu: Math.random() * 100,
      memory: Math.random() * 100,
      disk: Math.random() * 100,
      responseTime: Math.random() * 1000,
      throughput: Math.random() * 1000,
      errorRate: Math.random() * 5
    };
  };

  // 获取后端性能数据
  const { data: backendMetrics, loading: backendLoading, error } = useCache(
    `performance-metrics-${selectedTimeRange}`,
    fetchBackendMetrics,
    { ttl: 30000 } // 30秒缓存
  );

  /**
   * 模拟实时性能数据生成
   */
  const generatePerformanceData = () => {
    const newData: PerformanceData = {
      timestamp: Date.now(),
      cpu: Math.random() * 100,
      memory: Math.random() * 100,
      disk: Math.random() * 100,
      network: Math.random() * 100,
      responseTime: Math.random() * 1000,
      throughput: Math.random() * 1000,
      errorRate: Math.random() * 5
    };

    setPerformanceData(prev => {
      const updated = [...prev, newData];
      // 保持最近100条数据
      return updated.slice(-100);
    });
  };

  /**
   * 初始化数据并设置定时器
   */
  useEffect(() => {
    generatePerformanceData();
    const interval = setInterval(generatePerformanceData, 5000); // 每5秒更新一次
    return () => clearInterval(interval);
  }, []);

  /**
   * 性能建议数据
   */
  const recommendations: PerformanceRecommendation[] = useMemo(() => [
    {
      id: '1',
      type: 'critical',
      category: 'frontend',
      title: '优化首屏加载时间',
      description: '当前首屏加载时间为3.2秒，建议优化资源加载',
      impact: 'high',
      solution: '启用代码分割和懒加载，压缩资源文件'
    },
    {
      id: '2',
      type: 'warning',
      category: 'backend',
      title: 'API响应时间过长',
      description: '部分API响应时间超过1秒',
      impact: 'medium',
      solution: '优化数据库查询，添加缓存层'
    },
    {
      id: '3',
      type: 'info',
      category: 'database',
      title: '数据库连接池优化',
      description: '可以考虑调整数据库连接池配置',
      impact: 'low',
      solution: '根据实际负载调整连接池大小'
    }
  ], []);

  /**
   * 计算健康度评分
   */
  const healthScore = useMemo(() => {
    if (!backendMetrics) return 0;

    const scores = [
      backendMetrics.cpu < 80 ? 100 : backendMetrics.cpu < 90 ? 70 : 40,
      backendMetrics.memory < 80 ? 100 : backendMetrics.memory < 90 ? 70 : 40,
      backendMetrics.responseTime < 500 ? 100 : backendMetrics.responseTime < 1000 ? 70 : 40,
      backendMetrics.errorRate < 1 ? 100 : backendMetrics.errorRate < 3 ? 70 : 40
    ];

    return Math.round(scores.reduce((a, b) => a + b, 0) / scores.length);
  }, [backendMetrics]);

  /**
   * 性能数据表格列配置
   */
  const performanceColumns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (timestamp: number) => new Date(timestamp).toLocaleTimeString(),
      width: 120
    },
    {
      title: 'CPU使用率',
      dataIndex: 'cpu',
      key: 'cpu',
      render: (value: number) => (
        <Progress
          type="line"
          percent={value}
          size="small"
          status={value > 80 ? 'exception' : value > 60 ? 'normal' : 'success'}
        />
      ),
      width: 150
    },
    {
      title: '内存使用率',
      dataIndex: 'memory',
      key: 'memory',
      render: (value: number) => (
        <Progress
          type="line"
          percent={value}
          size="small"
          status={value > 80 ? 'exception' : value > 60 ? 'normal' : 'success'}
        />
      ),
      width: 150
    },
    {
      title: '响应时间',
      dataIndex: 'responseTime',
      key: 'responseTime',
      render: (value: number) => `${value.toFixed(2)}ms`,
      width: 120
    },
    {
      title: '吞吐量',
      dataIndex: 'throughput',
      key: 'throughput',
      render: (value: number) => `${value.toFixed(0)}/s`,
      width: 120
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card title="系统性能监控" style={{ marginBottom: '24px' }}>
        <Row gutter={[16, 16]}>
          {/* 总体健康度 */}
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="系统健康度"
                value={healthScore}
                suffix="/ 100"
                prefix={<CheckCircleOutlined />}
                valueStyle={{ color: healthScore > 80 ? '#52c41a' : healthScore > 60 ? '#faad14' : '#ff4d4f' }}
              />
            </Card>
          </Col>

          {/* CPU使用率 */}
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="CPU使用率"
                value={backendMetrics?.cpu || 0}
                suffix="%"
                prefix={<ThunderboltOutlined />}
                valueStyle={{
                  color: (backendMetrics?.cpu || 0) > 80 ? '#ff4d4f' :
                         (backendMetrics?.cpu || 0) > 60 ? '#faad14' : '#52c41a'
                }}
              />
            </Card>
          </Col>

          {/* 内存使用率 */}
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="内存使用率"
                value={backendMetrics?.memory || 0}
                suffix="%"
                prefix={<DatabaseOutlined />}
                valueStyle={{
                  color: (backendMetrics?.memory || 0) > 80 ? '#ff4d4f' :
                         (backendMetrics?.memory || 0) > 60 ? '#faad14' : '#52c41a'
                }}
              />
            </Card>
          </Col>

          {/* 平均响应时间 */}
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="平均响应时间"
                value={backendMetrics?.responseTime || 0}
                suffix="ms"
                prefix={<ClockCircleOutlined />}
                valueStyle={{
                  color: (backendMetrics?.responseTime || 0) > 800 ? '#ff4d4f' :
                         (backendMetrics?.responseTime || 0) > 500 ? '#faad14' : '#52c41a'
                }}
              />
            </Card>
          </Col>
        </Row>
      </Card>

      {/* 性能监控标签页 */}
      <Card>
        <Tabs
        defaultActiveKey="realtime"
        items={[
          {
            key: 'realtime',
            label: '实时监控',
            children: (
              <Table
                dataSource={[...performanceData].reverse()}
                columns={performanceColumns}
                rowKey="timestamp"
                pagination={{ pageSize: 10 }}
                size="small"
                scroll={{ x: 800 }}
              />
            )
          },
          {
            key: 'recommendations',
            label: '性能建议',
            children: (
              <Timeline>
                {recommendations.map((rec) => (
                  <Timeline.Item
                    key={rec.id}
                    color={
                      rec.type === 'critical' ? 'red' :
                      rec.type === 'warning' ? 'orange' : 'blue'
                    }
                    dot={
                      rec.type === 'critical' ? <WarningOutlined /> :
                      rec.type === 'warning' ? <WarningOutlined /> :
                      <CheckCircleOutlined />
                    }
                  >
                    <Alert
                      message={rec.title}
                      description={
                        <div>
                          <p>{rec.description}</p>
                          <p><strong>解决方案：</strong>{rec.solution}</p>
                          <div style={{
                            display: 'inline-block',
                            padding: '2px 8px',
                            borderRadius: '4px',
                            fontSize: '12px',
                            background:
                              rec.impact === 'high' ? '#fff2f0' :
                              rec.impact === 'medium' ? '#fff7e6' : '#f6ffed',
                            color:
                              rec.impact === 'high' ? '#ff4d4f' :
                              rec.impact === 'medium' ? '#fa8c16' : '#52c41a'
                          }}>
                            {rec.category} - {rec.impact}影响
                          </div>
                        </div>
                      }
                      type={rec.type === 'critical' ? 'error' : rec.type === 'warning' ? 'warning' : 'info'}
                      showIcon
                    />
                  </Timeline.Item>
                ))}
              </Timeline>
            )
          },
          {
            key: 'frontend',
            label: '前端性能',
            children: (
              <div style={{ padding: '24px' }}>
                <h4>前端组件性能</h4>
                <Row gutter={[16, 16]}>
                  <Col span={12}>
                    <Card size="small">
                      <Statistic title="渲染次数" value={renderCount} />
                    </Card>
                  </Col>
                  <Col span={12}>
                    <Card size="small">
                      <Statistic
                        title="平均渲染时间"
                        value={averageRenderTime}
                        suffix="ms"
                        precision={2}
                      />
                    </Card>
                  </Col>
                </Row>
              </div>
            )
          }
        ]}
      />
      </Card>

      {/* Web Vitals 监控组件 */}
      <WebVitalsMonitor />
    </div>
  );
};

export default PerformanceDashboard;